package com.search2.search;

import java.io.File;
import java.io.FilenameFilter;

import com.search2.search.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

public class Search extends Activity {
    
	private EditText mQueryText;	
	public enum SearchTypeEnum { QUESTIONS, ANSWER_WHOLE, ANSWER_TRIPLETS };
	// Default to triplets 
	private SearchTypeEnum mSearchType = SearchTypeEnum.ANSWER_TRIPLETS;
	
	//Definitions for Menus Options, Intent Request Code, Dialogs
	static final int MENU_OPTIONS = 0;
	static final int MENU_ABOUT = 1;
	static final int DIALOG_CHOSE_DATA_FILE = 0;
	static final int DIALOG_ABOUT= 1;	
	static final int REQUEST_VIEW_RESULTS = 1;
	
	/** Called when the activity is first created. 
	 *  Open the default database and set up the UI
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Set the view to search layout
        setContentView(R.layout.search_layout);
        
        //Setup the animation - items slide in from left to right
        LinearLayout lay = (LinearLayout) findViewById(R.id.linearLayoutSearch);
        AnimationSet set = new AnimationSet(true);
        Animation animation = new TranslateAnimation(
        		Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
        		Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f
        );
        
        animation.setDuration(500);
        set.addAnimation(animation);
        
        LayoutAnimationController controller = new LayoutAnimationController(set);//, 0.5f);          
        
        lay.setLayoutAnimation(controller);
        
        //Find the search button so we can set its visibility
        Button searchButton = (Button) findViewById(R.id.searchButton);
        
        //Open the application class and instruct it to open the default database
        SearchDbAdapter dbHelper = ((SearchDbAdapter)getApplication());
        if(!dbHelper.openDefault()) {
        	Toast.makeText(this, "Unable to open default data file", Toast.LENGTH_LONG).show();        	
        	searchButton.setVisibility(android.view.View.INVISIBLE);
        }
        
        //Clear the query text 
        mQueryText = (EditText) findViewById(R.id.queryEditText);
        mQueryText.setText("");
        
        //Set the radio button listener handlers
        final RadioButton questionsRb = (RadioButton) findViewById(R.id.questionsRadioButton);
        final RadioButton answersTripletsRb = (RadioButton) findViewById(R.id.answerTripletsRadioButton);
        final RadioButton answersWholeRb = (RadioButton) findViewById(R.id.answerWholeRadioButton);
        questionsRb.setOnClickListener(radio_listener);
        answersTripletsRb.setOnClickListener(radio_listener);
        answersWholeRb.setOnClickListener(radio_listener);
        
        //Default to Answer Triplets
        answersTripletsRb.setChecked(true);
        
        //Set the search button listener handler
        searchButton.setOnClickListener(button_listener);                
    }
    
    /*** Callback for the search button click
     * 
     * Pass the search query intent to the view results activity
     * 
     */
    private OnClickListener button_listener = new OnClickListener() {
    	public void onClick(View v) {
    		String queryText = mQueryText.getText().toString();
    		
    		//if searching questions or whole answers, we need at least 3 characters
    		if(mSearchType == SearchTypeEnum.QUESTIONS || mSearchType == SearchTypeEnum.ANSWER_WHOLE) {
            		if(queryText.length() < 3) {
            			Toast.makeText(v.getContext(), "Enter 3 or more characters", Toast.LENGTH_SHORT).show(); 
            			return;
            		}	
    		} else { //if searching answers triplets, we need 6 or 9
        		if(!(queryText.length() == 6 || queryText.length() == 9)) {
            			Toast.makeText(v.getContext(), "Enter 6 or 9 characters", Toast.LENGTH_SHORT).show(); 
            			return;
            		}
    		}
    		
    		//Add the query text and search type to the Intent
            Intent i = new Intent(v.getContext(), ViewResults.class);
            i.putExtra(SearchDbAdapter.QUERY, queryText);
            i.putExtra(SearchDbAdapter.SEARCH_TYPE, mSearchType.name());
            //i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            //Start the activity
            startActivityForResult(i,REQUEST_VIEW_RESULTS);
            overridePendingTransition(R.anim.slide_left,R.anim.push_left_out);
    	}
    };
    
    /*** Callback when a radio button is selected
     *   Store the search type
     */
    private OnClickListener radio_listener = new OnClickListener() {
    	public void onClick(View v) {
    		RadioButton rb = (RadioButton) v;
    		if(rb.getId() == R.id.questionsRadioButton) {
    			mSearchType = SearchTypeEnum.QUESTIONS;
    		} else if (rb.getId() == R.id.answerWholeRadioButton) {
    			mSearchType = SearchTypeEnum.ANSWER_WHOLE;
    		} else {
    			mSearchType = SearchTypeEnum.ANSWER_TRIPLETS;
    		}    		
    	}
    };

    /***
     * Callback for when the view results activity has finished
     * Clear the query text
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
    {    
    	//We don't really need to check the request and result as 
    	//we only have one other activity and we want to perform
    	//the same action regardless of the result
    	if(requestCode == REQUEST_VIEW_RESULTS) {
    		if(resultCode == RESULT_OK) {
    			mQueryText.setText("");
    		}
    	}
    	super.onActivityResult(requestCode, resultCode, intent);
    }
    
    /***
     * Called when the hardware BACK button pressed
     * Close the database
     */
	@Override
	public void onBackPressed() {
		SearchDbAdapter dbHelper = ((SearchDbAdapter)getApplication());
		dbHelper.close();
		super.onBackPressed();	
	}

	/***
	 * Called when the hardware MENU button pressed
	 * Create the menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {	
		menu.add(0,MENU_OPTIONS,0,"Select Data File");
		menu.add(0,MENU_ABOUT,0,"About");
		return true;
	}

	/***
	 * Filter for files with ".db" extension
	 * 
	 *
	 */
	private class DBFilter implements FilenameFilter {
		        public boolean accept(File dir, String name) {
		                return (name.endsWith(".db"));
		        }
		}
	
	/***
	 * Called when a dialog is to be created - e.g. after
	 * selecting an item from the options menu
	 */
	protected Dialog onCreateDialog(int id) {    
		Dialog dialog;    
		switch(id) {    
		case DIALOG_CHOSE_DATA_FILE:   
			//Get a list of *.db files on the SD Card
			final CharSequence[] items;
			File fileList[] = Environment.getExternalStorageDirectory().listFiles(new DBFilter());
			items = new String[fileList.length];
			for (int i = 0;i<fileList.length;i++) {
				items[i] = fileList[i].getName(); 
			} 			
			//Create the dialog to display the list
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Pick a file");
			//Radio buttons - single choice from the list
			builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {    
				public void onClick(DialogInterface dialog, int item) {   
					String chosenFile = (String) items[item];
					//Try and open the selected database file
					SearchDbAdapter dbHelper = ((SearchDbAdapter)getApplication());
					if(dbHelper.openFile(chosenFile)) {
						//Database file opened ok - enable the Search button
						Toast.makeText(getApplicationContext(), chosenFile + " selected", Toast.LENGTH_SHORT).show();						
						Button searchButton = (Button) findViewById(R.id.searchButton);					
						searchButton.setVisibility(android.view.View.VISIBLE);  						
					} else {
						Toast.makeText(getApplicationContext(), "Unable to open " + chosenFile, Toast.LENGTH_SHORT).show();
					}				
					dialog.dismiss();
					}
				});
			dialog = builder.create();      
			break;    
		case DIALOG_ABOUT:     
			//Create an About box
			AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
			builder1.setTitle("About")
				    .setMessage("Search2 \n" +
								"\u00A9" + " 2011 JO")       
					.setCancelable(true)       
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {           
						public void onClick(DialogInterface dialog, int id) {                
							dialog.cancel();            
						}       
					});       
			dialog = builder1.create();     
			break;    
		default:        
			dialog = null;    
		}    
		return dialog;
	}
	
	/***
	 * Called when an item from the options menu selected
	 * Shows the appropriate dialog box
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId())
		{
		case MENU_OPTIONS:
			showDialog(DIALOG_CHOSE_DATA_FILE);
			break;
		case MENU_ABOUT:
			showDialog(DIALOG_ABOUT);
			break;
		}

		return true;

	}
    
}